#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Simple background music generator
Generate suitable background music for card games
"""

import numpy as np
import wave
import os

def generate_tone(frequency, duration, sample_rate=44100, amplitude=0.3):
    """Generate tone with specified frequency and duration"""
    frames = int(duration * sample_rate)
    arr = np.zeros(frames)
    
    for i in range(frames):
        # Generate basic tone using sine wave
        arr[i] = amplitude * np.sin(2 * np.pi * frequency * i / sample_rate)
        
        # Add harmonics to make sound richer
        arr[i] += 0.1 * amplitude * np.sin(4 * np.pi * frequency * i / sample_rate)
        arr[i] += 0.05 * amplitude * np.sin(6 * np.pi * frequency * i / sample_rate)
    
    return arr

def apply_envelope(audio, attack=0.1, decay=0.1, sustain=0.7, release=0.2):
    """Apply ADSR envelope"""
    length = len(audio)
    envelope = np.ones(length)
    
    # Attack
    attack_frames = int(attack * length)
    for i in range(attack_frames):
        envelope[i] = i / attack_frames
    
    # Decay
    decay_frames = int(decay * length)
    for i in range(attack_frames, attack_frames + decay_frames):
        t = (i - attack_frames) / decay_frames
        envelope[i] = 1 - (1 - sustain) * t
    
    # Sustain (maintain current value)
    sustain_start = attack_frames + decay_frames
    sustain_frames = int((1 - attack - decay - release) * length)
    for i in range(sustain_start, sustain_start + sustain_frames):
        envelope[i] = sustain
    
    # Release
    release_start = sustain_start + sustain_frames
    for i in range(release_start, length):
        t = (i - release_start) / (length - release_start)
        envelope[i] = sustain * (1 - t)
    
    return audio * envelope

def generate_chord(frequencies, duration, sample_rate=44100):
    """Generate chord"""
    chord = np.zeros(int(duration * sample_rate))
    for freq in frequencies:
        tone = generate_tone(freq, duration, sample_rate, amplitude=0.2)
        chord += tone
    return apply_envelope(chord)

def generate_background_music():
    """Generate background music"""
    sample_rate = 44100
    
    # Define basic frequencies (C major scale)
    # C4, E4, G4, C5 (chord)
    c_major = [261.63, 329.63, 392.00, 523.25]
    # F4, A4, C5, F5
    f_major = [349.23, 440.00, 523.25, 698.46]
    # G4, B4, D5, G5
    g_major = [392.00, 493.88, 587.33, 783.99]
    # A4, C5, E5, A5
    a_minor = [440.00, 523.25, 659.25, 880.00]
    
    # Create music sequence
    music_sequence = []
    
    # First section: peaceful beginning
    music_sequence.append(generate_chord(c_major, 2.0))
    music_sequence.append(generate_chord(a_minor, 2.0))
    music_sequence.append(generate_chord(f_major, 2.0))
    music_sequence.append(generate_chord(g_major, 2.0))
    
    # Second section: slightly more active
    music_sequence.append(generate_chord(c_major, 1.5))
    music_sequence.append(generate_chord(g_major, 1.5))
    music_sequence.append(generate_chord(a_minor, 1.5))
    music_sequence.append(generate_chord(f_major, 1.5))
    
    # Third section: back to peaceful
    music_sequence.append(generate_chord(f_major, 2.5))
    music_sequence.append(generate_chord(c_major, 2.5))
    
    # Combine all segments
    full_music = np.concatenate(music_sequence)
    
    # Add fade in/out effects
    fade_frames = int(0.5 * sample_rate)  # 0.5 second fade
    
    # Fade in
    for i in range(fade_frames):
        full_music[i] *= i / fade_frames
    
    # Fade out
    for i in range(fade_frames):
        full_music[-(i+1)] *= i / fade_frames
    
    # Normalize volume
    max_val = np.max(np.abs(full_music))
    if max_val > 0:
        full_music = full_music / max_val * 0.8  # 留一些余量
    
    return full_music, sample_rate

def save_as_wav(audio_data, sample_rate, filename):
    """Save as WAV file"""
    # Convert to 16-bit integer
    audio_int = (audio_data * 32767).astype(np.int16)
    
    with wave.open(filename, 'w') as wav_file:
        wav_file.setnchannels(1)  # 单声道
        wav_file.setsampwidth(2)  # 16位
        wav_file.setframerate(sample_rate)
        wav_file.writeframes(audio_int.tobytes())

if __name__ == "__main__":
    print("正在生成背景音乐...")
    
    # 生成音乐
    music, sample_rate = generate_background_music()
    
    # 保存为WAV文件
    output_path = os.path.join("assets", "audio", "background_music.wav")
    os.makedirs(os.path.dirname(output_path), exist_ok=True)
    save_as_wav(music, sample_rate, output_path)
    
    print(f"背景音乐已生成并保存到: {output_path}")
    print(f"时长: {len(music) / sample_rate:.1f} 秒")
    print("注意：这是一个简单的程序生成音乐，实际项目中建议使用专业制作的音乐文件。")